import { loginByUsername, logout, getUserInfo, getUserInfo_t, getRouter } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import permission from './permission'
import admin_router from '@/router/admin_router'
const user = {
  state: {
    user: '',
    status: '',
    code: '',
    token: getToken(),
    name: '',
    avatar: '',
    introduction: '',
    roles: [],
    setting: {
      articlePlatform: []
    },
    udi: '',
    ROLE: '',
    show_list: ''
  },

  mutations: {
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_UID: (state, uid) => {
      state.uid = uid
    },
    SET_ROUTER: (state, ROUTER) => {
      state.ROUTER = ROUTER
    },
    SET_ROLE: (state, ROLE) => {
      state.ROLE = ROLE
    },
    SET_LIST: (state, list) => {
      state.list = list
    }
  },

  actions: {
    // 用户名登录
    LoginByUsername({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        loginByUsername(username, userInfo.password)
          .then((response) => {
            const data = response.data
            commit('SET_TOKEN', data.userId)
            setToken(response.data.userId)
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 获取用户信息
    GetUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        // getUserInfo().then(response => {
        //   if (!response.data) { // 由于mockjs 不支持自定义状态码只能这样hack
        //     reject('error')
        //   }

        //   const data = response.data
        //   if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
        //     commit('SET_ROLES', data.roles)
        //   } else {
        //     reject('getInfo: roles must be a non-null array !')
        //   }

        //   commit('SET_NAME', data.name)
        //   commit('SET_AVATAR', data.avatar)
        //   commit('SET_INTRODUCTION', data.introduction)
        //   resolve(response)
        // }).catch(error => {
        //   reject(error)
        // })
        getUserInfo_t()
          .then((response) => {
            const data = response.data
            if (data.code === 200) {
              resolve(response)
              commit('SET_NAME', data.name)

              commit('SET_ROLES', data.roleIdList || [])
            } else {
              reject('getuserinfo not success')
            }
          })
          .catch((err) => {
            reject(err)
            console.log(err)
          })
      })
    },
    GetRoutes({ commit, state }) {
      return new Promise((resolve, reject) => {
        getRouter().then((rep) => {
          const menuList = rep.data.menuList

          menuList.forEach((currentValue, index, arr) => {
            // menuList[index].path
            if (menuList[index].list) {
              // 有子
              const menuList_now = menuList[index]
              menuList_now.list.forEach((val, index, arr) => {
                const temp_name = menuList_now.list[index].name // 子的name

                const f_temp_name = menuList_now.name // fu name

                admin_router.forEach((currentValue, index_inner, arr) => {
                  if (admin_router[index_inner].c_name === f_temp_name) {
                    menuList_now.path = admin_router[index_inner].path
                    menuList_now.meta = { icon: '' }
                    admin_router[index_inner].meta.icon ? menuList_now.meta.icon = admin_router[index_inner].meta.icon : ''
                  }
                  // 有名字

                  admin_router[index_inner].children.forEach((cur, index_inner_i, arr) => {
                    if (
                      admin_router[index_inner].children[index_inner_i].meta.c_name === temp_name
                    ) {
                      menuList_now.list[index].meta = { icon: '' }
                      menuList_now.list[index].meta.icon = admin_router[index_inner].children[index_inner_i].meta.icon
                      menuList_now.list[index].path =
                        admin_router[index_inner].children[index_inner_i].path
                        // menuList_now.list[index].children =  admin_router[index_inner].children[index_inner_i]
                    } else {
                      // 没有名字
                      console.log('no')
                    }
                  })
                })
              })
              menuList[index] = menuList_now
            } else {
              // 没有数据
              // admin_router[index].path = admin_router[index].path;
            }
          })

          rep.data.menuList = menuList
          commit('NEW_SET_ROUTERS', rep.data)
          resolve(rep)
        })
      }).catch((err) => {
        reject(err)
      })
    },

    // 第三方验证登录
    // LoginByThirdparty({ commit, state }, code) {
    //   return new Promise((resolve, reject) => {
    //     commit('SET_CODE', code)
    //     loginByThirdparty(state.status, state.email, state.code).then(response => {
    //       commit('SET_TOKEN', response.data.token)
    //       setToken(response.data.token)
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            removeToken()
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },

    // 动态修改权限
    ChangeRoles({ commit }, role) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', role)
        setToken(role)
        getUserInfo(role).then((response) => {
          const data = response.data
          commit('SET_ROLES', data.roles)
          commit('SET_NAME', data.name)
          commit('SET_AVATAR', data.avatar)
          commit('SET_INTRODUCTION', data.introduction)
          resolve()
        })
      })
    }
  }
}

export default user
